package com.soriya.switcher.component

import android.util.Log
import android.view.Surface
import androidx.annotation.OptIn
import androidx.camera.core.CameraSelector
import androidx.camera.core.ExperimentalLensFacing
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.blankj.utilcode.util.ToastUtils
import com.soriya.switcher.util.PermissionUtils


private const val TAG = "MainComponent"

@OptIn(ExperimentalLensFacing::class)
@Composable
fun CameraPreview(modifier: Modifier = Modifier) {
    Box(
        modifier = modifier
            .clip(RoundedCornerShape(6.dp))
    ) {
        val lifecycleOwner = LocalLifecycleOwner.current
        val context = LocalContext.current
        AndroidView(
            factory = { context ->
                PreviewView(context)
            },
            update = { previewView ->
                var cameraSelector: CameraSelector? = null
                var cameraProvider: ProcessCameraProvider?

                val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
                cameraProviderFuture.addListener({
                    try {
                        cameraProvider = cameraProviderFuture.get()

                        val externalCamera = CameraSelector.Builder().requireLensFacing(
                            CameraSelector.LENS_FACING_EXTERNAL).build()

                        if (cameraProvider!!.hasCamera(CameraSelector.DEFAULT_BACK_CAMERA)) {
                            Log.d(TAG, "hasCamera: back")
                            cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
                        } else if (cameraProvider.hasCamera(CameraSelector.DEFAULT_FRONT_CAMERA)) {
                            Log.d(TAG, "hasCamera: front")
                            cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
                        } else if (cameraProvider.hasCamera(externalCamera)) {
                            Log.d(TAG, "hasCamera: external")
                            cameraSelector = externalCamera
                        }

                        if (cameraSelector == null) {
                            ToastUtils.showLong("未找到摄像头")
                            return@addListener
                        }

                        val preview = Preview.Builder()
                            .setTargetRotation(Surface.ROTATION_0)
                            .build()
                        preview.surfaceProvider = previewView.surfaceProvider

                        if (PermissionUtils.checkCameraPermission { isAllGranted, granted, deniedForever, denied ->
                            Log.d(TAG, "CameraPreview: $isAllGranted")
                            if (isAllGranted) {
                                cameraProvider.unbindAll()
                                cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview)
                            }
                        }) {
                            cameraProvider.unbindAll()
                            cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview)
                        }
                    } catch (e: Exception) {
                        ToastUtils.showLong("相机打开失败")
                    }
                }, ContextCompat.getMainExecutor(context))
            },
            modifier = Modifier.fillMaxSize()
        )
    }
}